using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;

namespace Web.Ajax.Controls
{
	[ToolboxData("<{0}:TabStrip runat=\"server\"></{0}:TabStrip>")]
	[ControlBuilderAttribute(typeof(TabStripBuilder))]
	[ParseChildren(false)]   
	public class TabStrip : AjaxControl
	{
		#region Constructor
		public TabStrip()
		{
            //Height is the height of the tab content, not the overall height including the titles.
			Height = new Unit("100%");
			Width = new Unit("100%");
			ExpandPad = 8;
		} 
		#endregion

		#region OnInit
		protected override void OnInit(EventArgs e)
		{            
			base.OnInit(e);
            Web.Ajax.Page p = Page as Web.Ajax.Page;
            if (p != null)
            {
                p.RegisterStyleSheet(Resources.StyleSheets.Tabs);
                p.RegisterJavascriptFile(Resources.Javascript.Tabs);
            }
		} 
		#endregion

		#region Tabs
		private List<Tab> tabs;
		/// <summary>
		/// The Tab Collection.
		/// </summary>
		public List<Tab> Tabs
		{
			get
			{
				if(tabs==null)
				{
					tabs=new List<Tab>();
					for (int i = 0; i < Controls.Count; i++)
					{
						Tab t = Controls[i] as Tab;
						if (t != null)
							Tabs.Add(t);
					}
				}
				return tabs;
			}
		} 
		#endregion

        public string SelectedTabId
        {
            get
            {
                for (int i = 0; i < Tabs.Count; i++)
                {
                    if (Tabs[i].Selected)
                        return Tabs[i].JavascriptId;
                }
                return "null";
            }
        }

        private string topPadding = "0px";
        public string TopPadding
        {
            get
            {
                return topPadding;
            }
            set
            {
                topPadding = value;
            }
        }

		/*
        private Unit? minHeight = null;
        public Unit? MinHeight
        {
            get { return minHeight; }
            set { minHeight = value; }
        }*/

		public bool Expand
		{
			get;
			set;
		}

		public int MinHeight = 100;

		public int ExpandPad
		{
			get;
			set;
		}

		public bool Resize
		{
			get;
			set;
		}

        #region Render
        protected override void Render(HtmlTextWriter writer)
		{

			var w = "";
			if(Width.ToString()!="100%")
				w="width:" + Width.ToString() + ";"; 


            writer.Write("<div class=\"TabStrip\" style=\""+ w + "padding-top:"+TopPadding.ToString()+";\">");
            writer.Write("<table cellspacing=0 cellpadding=0><tr>");
			writer.Write("<td class=\"TabFill\">");
			if (TabHeadingLeft != null)
				TabHeadingLeft.RenderHtml(writer);
			//writer.Write("&nbsp;&nbsp;&nbsp;");
			writer.Write("</td>");
			StringBuilder html = new StringBuilder();
			for (int i = 0; i < Tabs.Count; i++)
			{
				Tab Tab = Tabs[i];
				if (!Tab.Visible)
					continue;
				string id = Tab.JavascriptId + "_b";
				html.Append("<td id=\""+id+"\" class=\"TabFill#SEL\">");
				if (!Tab.Selected)
					html.Replace("#SEL", "");
				else
					html.Replace("#SEL", "Selected");
				html.Append(Tab.RenderTitle());
				html.Append("</td>");
                html.Append("<td class=\"TabFill\"><div style=\"width:#WD#px;\"></div></td>");
			}
            html.Replace("#WD#", Configuration.Settings.Current.TabStrip.SpaceBetweenTabs.ToString());

			
            html.Append("<td class=\"TabFill\" style=\"width:100%;text-align:right;\">&nbsp;");
			//html.Append("<td>");
            writer.Write(html.ToString());
            if (TabHeadingRight != null)
                TabHeadingRight.RenderHtml(writer);
            writer.Write("<td>");
            writer.Write("</tr></table>");
			//writer.Write(html.ToString());
			base.Render(writer);
			writer.WriteLine("</div>");
            writer.WriteLine("<script type=\"text/javascript\">");
            writer.WriteLine("var "+JavascriptId+"=new Tabs('"+JavascriptId+"');");
            RenderProperty(writer, "SelectedTabId", SelectedTabId);
			if (Page.Browser == Browser.FireFox)
				ExpandPad -= 5;

			RenderProperty(writer, "Resize", Resize);
			RenderProperty(writer, "MinHeight", MinHeight);
			RenderProperty(writer, "ExpandPad", ExpandPad);
			var TabsJson = "[";
			bool first = true;
			foreach (Tab t in Tabs)
			{
				if (!first)
					TabsJson += ",";
				first = false;
				TabsJson += "{Id:'"+t.JavascriptId+"'"+(t.ContentLoadedFromUrl?(",ExpandPad:"+(this.ExpandPad).ToString()+""):"")+"}";
			}
			TabsJson += "]";
			writer.WriteLine(JavascriptId+".Tabs="+TabsJson+";");
			if (Expand||Resize)
				writer.WriteLine(JavascriptId + ".Expand();");
            writer.Write("</script>");
		}

        //Prevent the default begin and end tags from being rendered.
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
        }
		#endregion

		#region TabSelected
		/// <summary>
		/// Called by a child tab when it is selected so the TabStrip can update the other tabs, setting their 
		/// selected property to false. Do not use.
		/// </summary>
		/// <param name="Tab">The Selected Tab.</param>
		public void TabSelected(Tab Tab)
		{
			for (int i = 0; i < Tabs.Count; i++)
			{
				Tab t = Tabs[i];
				if (t != null && t!=Tab)
					t.Selected = false;
			}
		}   
		#endregion

		#region SelectTab
		/// <summary>
		/// 
		/// </summary>
		/// <param name="title"></param>
		public void SelectTab(Tab t)
		{
			if (t != null)
				t.Selected = true;
		} 
		#endregion

		#region ShowOnly
		/// <summary>
		/// 
		/// </summary>
		/// <param name="title"></param>
		public void ShowOnly(Tab t)
		{
			for (int i = 0; i < Tabs.Count; i++)
				Tabs[i].Visible = false;
			if (t != null)
			{
				Visible = true;
				t.Visible = true;
				t.Selected = true;
			}
		}
		#endregion

		#region TabHeadingLeft
		/// <summary>
		/// The TabHeadingLeft control if is exists as a child control.
		/// </summary>
		private TabHeadingLeft tabHeadingLeft;
		public TabHeadingLeft TabHeadingLeft
		{
			get
			{
				if (tabHeadingLeft == null)
				{
					for (int i = 0; i < Controls.Count; i++)
					{
						if (Controls[i] is TabHeadingLeft)
							tabHeadingLeft = (TabHeadingLeft)Controls[i];
					}
				}
				return tabHeadingLeft;
			}
		} 
		#endregion

		#region TabHeadingRight
		/// <summary>
		/// The TabHeadingRight control if is exists as a child control.
		/// </summary>
		private TabHeadingRight tabHeadingRight;
		public TabHeadingRight TabHeadingRight
		{
			get
			{
				if (tabHeadingRight == null)
				{
					for (int i = 0; i < Controls.Count; i++)
					{
						if (Controls[i] is TabHeadingRight)
							tabHeadingRight = (TabHeadingRight)Controls[i];
					}
				}
				return tabHeadingRight;
			}
		}
		#endregion


	}

	#region TabStripBuilder
	/// <summary>
	/// The Control Builder for the TabStrip class. Only permits the "Tab" tag as a child element.
	/// </summary>
	internal class TabStripBuilder : ControlBuilder
	{
		public override Type GetChildControlType(string tagName, System.Collections.IDictionary attribs)
		{
			tagName = tagName.ToLower();
			if (tagName == "tab")
				return typeof(Tab);
			if (tagName == "left")
				return typeof(TabHeadingLeft);
			if (tagName == "right")
				return typeof(TabHeadingRight);
			return null;
		}
	}
	#endregion
}
